package com.macro.mall.portal.root.upload;

import com.macro.mall.common.utils.DateUtil;
import com.macro.mall.domain.PmsAlbumPicResult;
import com.macro.mall.domain.UploadResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.UUID;

public abstract class UploadFileService {

    @Value("${jhh.file.path}")
    private String upload_path;

    public UploadResult uploadFile(MultipartHttpServletRequest multiRequest) throws Exception {
        long startTime = System.currentTimeMillis();
        ArrayList<PmsAlbumPicResult> uploadResults = new ArrayList<>();
        //获取multiRequest 中所有的文件名
        Iterator iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            //一次遍历所有文件
            MultipartFile file = multiRequest.getFile(iter.next().toString());
            File newFile = this.createFile(file);
            PmsAlbumPicResult uploadResult = saveMassage(newFile);
            uploadResults.add(uploadResult);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("运行时间：" + String.valueOf(endTime - startTime) + "ms");
        UploadResult uploadResult = new UploadResult();
        uploadResult.setFiles(uploadResults);
        return uploadResult;
    }

    public abstract PmsAlbumPicResult saveMassage(File file);

    protected final File createFile(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
        Iterator<ImageReader> iters = ImageIO.getImageReaders(iis);
        if (!iters.hasNext()) {
            throw new RuntimeException("请上传图片!!!!!");
        }
        if (file != null) {
            String timeNow = DateUtil.dateTimeNow(DateUtil.YYYYMMDD);
            String filename = file.getOriginalFilename();
            String ext = null;
            if (filename.contains(".")) {
                ext = filename.substring(filename.lastIndexOf("."));
            } else {
                ext = "";
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String path = upload_path + File.separator + timeNow + File.separator + uuid + ext;
            File targetFile = new File(path);
            targetFile.getParentFile().mkdirs();
            targetFile.createNewFile();
            //上传
            file.transferTo(targetFile);
            return targetFile;
        }
        return null;
    }
}
